package column

import (
	"fmt"
	"game/game-db/orm/metag"
	"reflect"
	"strings"
	"time"
	"unsafe"
)

type TimeColumnMeta struct {
	ColumnMeta
}

func (t *TimeColumnMeta) FillValue(objField reflect.Value, fieldValue reflect.Value) {
	timeStr := fieldValue.Interface().(string)

	value, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local)
	if err != nil {
		fmt.Printf("字段%v在解释值%v时发生错误%v\n", t.fieldName, timeStr, err)
	} else {
		setValue(objField, reflect.ValueOf(value))
	}
}
func (t *TimeColumnMeta) TakeValue(objField reflect.Value) interface{} {
	if objField.CanInterface() {
		return objField.Interface()
	} else {
		objField = reflect.NewAt(objField.Type(), unsafe.Pointer(objField.UnsafeAddr())).Elem()
		return objField.Interface()
	}
}

func (t *TimeColumnMeta) DbColumnType() string {
	return "datetime"
}

func (t *TimeColumnMeta) DefaultValue() string {
	if t.defaultValue == "" {
		return "DEFAULT NULL"
	} else {
		return fmt.Sprintf("DEFAULT '%s'", t.defaultValue)
	}
}

func (t *TimeColumnMeta) IsChange(dbColumnType string, dbColumnExtra string) bool {
	return !strings.HasPrefix(dbColumnType, "datetime")
}

func NewTimeField(structField reflect.StructField, columnMetag metag.ColumnMetag) IColumnMeta {
	var meta TimeColumnMeta
	meta.fillBaseValue(structField, columnMetag)
	return &meta
}
